package br.com.abril.profile;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class Preferences {

	@Autowired
	private PreferenceRepository repository;
	
	public Map<PreferenceType, Preference> cache;
	
	public Preferences() {
		cache = new HashMap<PreferenceType, Preference>();
	}
	
	@PostConstruct
	public void init () {
		loadPreferences();
	}
	
	@Transactional(readOnly=true)
	public void loadPreferences() {
		List<Preference> preferences = repository.findAll();
		for (Preference preference : preferences) {
			cache.put( PreferenceType.valueOf(preference.getName()) , preference);
		}
	}

	public Preference get(PreferenceType type) {
		return cache.get(type);
	}	

	public String getValue(PreferenceType type) {
		if (!cache.containsKey(type)) return "";
		return cache.get(type).getValue();
	}	

	public Boolean getBooleanValue(PreferenceType type) {
		if (!cache.containsKey(type)) return false;
		return Boolean.parseBoolean( cache.get(type).getValue() );
	}	

	public Integer getIntegerValue(PreferenceType type) {
		if (!cache.containsKey(type)) return 0;
		return Integer.parseInt( cache.get(type).getValue() );
	}	

	@Transactional
	public void saveLocalCache() {
		
		Collection<Preference> preferences = cache.values();
		
		repository.save(preferences);
		
	}
	
}
